package com.itheima.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.Address;
import com.itheima.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author 王加鑫
 * @Date 2021/07/26 20:42
 * @Since JDK 1.8
 */
@Controller
public class AjaxController {

    @RequestMapping("/ajaxController")
    public String ajaxController(@RequestBody String message){
        System.out.println("message = " + message);
        return "page.jsp";
    }

    @RequestMapping("/ajaxPojoToController")
    @ResponseBody
    public String ajaxPojoToController(@RequestBody User user){
        System.out.println("user = " + user);
        return "page.jsp";
    }


    @RequestMapping("/ajaxListToController")
    @ResponseBody
    public String ajaxListToController(@RequestBody List<User> userList){
        System.out.println("userList = " + userList);
        return "page.jsp";
    }

    @RequestMapping("/ajaxReturnString")
    @ResponseBody
    public void ajaxReturnString(HttpServletResponse resp) throws IOException {
        resp.getWriter().write("Hello SpringMVC");
    }

    @RequestMapping("/ajaxReturnJsonForGet")
    @ResponseBody
    public String ajaxReturnJsonForGet(@RequestParam("name") String name,@RequestParam("age") Integer age) throws JsonProcessingException {
        System.out.println("name = " + name);
        System.out.println("age = " + age);
        return new ObjectMapper().writeValueAsString(new User(name,age));
    }

    @RequestMapping("/ajaxReturnJsonForPost")
    @ResponseBody
    public String ajaxReturnJsonForPost(@RequestBody User user) throws JsonProcessingException {
        System.out.println("user = " + user);
        return new ObjectMapper().writeValueAsString(user);
    }

    @RequestMapping("/ajaxReturnJsonList")
    @ResponseBody
    public List ajaxReturnJsonList() throws JsonProcessingException {

        List<User> userList = new ArrayList<>();
        User user1 = new User("张三",23);
        User user2 = new User("李四",24);
        userList.add(user1);
        userList.add(user2);
        return userList;
    }


}
